package com.hong610.net.connection;

import com.hong610.net.enums.NetAgreement;
import com.hong610.net.http.client.SSLClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

/**
 * HttpClient连接对象
 * Created by Hong on 2016/12/31.
 */
public class HttpConnection {

    private static CloseableHttpClient httpClient = null;

    /**
     * 获取HttpClient对象
     *
     * @param netAgreement
     * @return HttpClient对象
     */
    public static CloseableHttpClient getConnenction(NetAgreement netAgreement) {
        try {
            if (NetAgreement.HTTP == netAgreement) {
                if (httpClient == null)
                    httpClient = HttpClientBuilder.create().build();
                return httpClient;
            } else if (NetAgreement.HTTPS == netAgreement) {
                if (httpClient == null)
                    httpClient = SSLClient.createSSLDefault();
                return httpClient;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static CloseableHttpClient getHttpsConnenctionCret(String cretPath, String password) {
        try {
            httpClient = SSLClient.createSSLCret(cretPath, password.toCharArray());
            return httpClient;
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        }
        return null;
    }
}
